<?php
/**
 * Created by PhpStorm.
 * User: Dave
 * Date: 2018/4/10
 * Time: 14:45
 */

namespace Biz\service;

use Biz\model\activity\ActivityRegisterGoods;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Biz\model\ShopSpecial as mShopSpecial;
use Biz\model\ShopSpecialTempl as mShopSpecialTempl;
use Biz\model\ShopSpecialGoods as mShopSpecialGoods;
use Biz\service\activity\AllActivityInfo;
use Biz\service\CarouselBanner as sCarouselBanner;
use Biz\service\GoodsDetail as sGoodsDetail;
use Biz\pockets\serviceTrait\_Async;
use Biz\service\Share as sShare;
use Doraemon\tools\ImgUrl;
use Biz\validate\ShopSpecial as vShopSpecial;
use Biz\cache\ShopSpecial as cShopSpecial;
use Biz\tools\BizUrl as toolsBizUrl;
use Biz\tools\SensorsApi as tSensorsApi;
use Biz\tools\Link as tLink;
use Biz\tools\BizUrl as tBizUrl;
use Biz\cache\ShopRecommendSpecial as cShopRecommendSpecial;
use Biz\service\Goods as sGoods;
use Doraemon\tools\Log as tLog;
use League\Flysystem\Exception;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\model\SelectGoodsLog as mSelectGoodsLog;
/**
 * @deprecated
 */
class ShopSpecial
{
    const SMALL_PROGRAM_SPECIAL = 'smallprogram';
    const INNER_LINK = '&in_app=1&';
    const OUTER_LINK = '&in_app=2&';
    public static $cacheSpecialData = null;
    public static $smallProgramSpecial = null;
    use _Async;

    private static function _getSpecialData($specialId)
    {
        if(!isset(self::$cacheSpecialData[$specialId]) || !self::$cacheSpecialData[$specialId]) {
            self::$cacheSpecialData[$specialId] = cShopSpecial::getSpecial($specialId);
        }
    }

    public static function getActivityData($specialId)
    {
        $specialData = null;
        self::getInfoBySpecialId($specialId);
        $cacheSpecialData = self::$cacheSpecialData[$specialId];
        if ($cacheSpecialData) {
            $specialData = $cacheSpecialData['info'];
        }

        return $specialData ?: [];
    }

    /*
     * 查询专题
     * **/
    public static function getSpecials($type, $isLarge, $specialTime, $field = '*')
    {
        return mShopSpecial::getSpecials($type, $isLarge, $specialTime, $field);
    }

    public static function admAddSpecial($data, $adminId)
    {
        $scenes = 'create';
        if (!vShopSpecial::validate($data, $scenes)) {
            $msg = vShopSpecial::firstError();
            die($msg);
        }

        $specialInfo = [
            'special_type' => $data['special_type'],
            'special_title' => $data['special_title'],
            'share_title' => $data['share_title'],
            'share_desc' => $data['share_desc'],
            'shop_img' => $data['shop_img'],
            'special_info_img' => $data['special_info_img'],
            'share_img' => $data['share_img'],
            'special_desc' => $data['special_desc'],
            'relation_id' => $data['relation_id'],
            'start_time' => $data['start_time'],
            'end_time' => $data['end_time'],
            'is_large_special' => $data['is_large_special'],
            'sort' => $data['sort'],
            'small_sort' => $data['small_sort'],
            'admin_id' => $adminId,
        ];
        if (!empty($data['special_goods'])) {
            $result = mShopSpecial::action(function () use ($specialInfo, $data, $adminId) {
                $specialId = mShopSpecial::addSpecial($specialInfo);
                if (!$specialId) {
                    return false;
                }
                $result = self::formatAndAddTemplGoods($specialId, $data['special_type'], $data['templ'], $data['special_goods'], $data['goods_desc'], $data['goods_price'], $data['goods_sort']);
                if ($result) {
                    return $specialId;
                } else {
                    return false;
                }
            });
            return $result;
        } else {
            throw new \Exception('商品信息不能为空');
        }
        return $result;
    }

    public static function admUpdateSpecialInfoById($specialId, $data, $adminId)
    {
        $scenes = 'update';
        if (!vShopSpecial::validate($data, $scenes)) {
            $msg = vShopSpecial::firstError();
            die($msg);
        }
        $specialInfo = [
            'special_type' => $data['special_type'],
            'special_title' => $data['special_title'],
            'share_title' => $data['share_title'],
            'share_desc' => $data['share_desc'],
            'shop_img' => $data['shop_img'],
            'special_info_img' => $data['special_info_img'],
            'share_img' => $data['share_img'],
            'special_desc' => $data['special_desc'],
            'relation_id' => $data['relation_id'],
            'start_time' => $data['start_time'],
            'end_time' => $data['end_time'],
            'is_large_special' => $data['is_large_special'],
            'sort' => $data['sort'],
            'small_sort' => $data['small_sort'],
            'admin_id' => $adminId,
        ];

        $result = mShopSpecial::action(function () use ($specialId, $specialInfo, $data, $adminId) {
            $specialId = mShopSpecial::updateSpecialInfoById($specialId, $specialInfo);
            if (!$specialId) {
                return false;
            }
            $result = self::formatAndAddTemplGoods($specialId, $data['special_type'], $data['templ'], $data['special_goods'], $data['goods_desc'], $data['goods_price'], $data['goods_sort']);
            if ($result) {
                return $specialId;
            } else {
                return false;
            }
        });
        return $result;
    }

    /**
     * 添加专题商品（调用层需要用事物）
     * @param $specialId
     * @param $specialType
     * @param $specialTempl
     * @param $specialGoods
     * @param $specialGoodsDesc
     * @param $specialGoodsPrice
     * @param $specialGoodsSort
     * @return array|bool
     * @throws \Exception
     */
    private static function formatAndAddTemplGoods($specialId, $specialType, $specialTempl, $specialGoods, $specialGoodsDesc, $specialGoodsPrice, $specialGoodsSort)
    {
        $specialTemplGoods = [];
        foreach ($specialGoods as $key => $val) {
            $templData = [
                'special_type' => $specialType,
                'type' => mShopSpecialTempl::SPECIAL_GOODS,
                'special_id' => $specialId,
                'sort' => $specialGoodsSort[$key],
                'status' => mShopSpecialTempl::STATUS_PASSED,
            ];
            $templId = $specialTempl[$key];
            if ($templId) {
                $result = mShopSpecialTempl::updateSpecialTempl(['special_id' => $specialId, 'id' => $specialTempl[$key]], $templData);
                if (!$result) {
                    throw new Exception('添加专题商品失败');
                }
            } else {
                $templId = mShopSpecialTempl::addSpecialTempl($templData);
            }
            if ($templId) {
                $specialTemplGoods[$val] = [
                    'special_id' => $specialId,
                    'special_type' => $specialType,
                    'templ_id' => $templId,
                    'goods_id' => $val,
                    'goods_desc' => $specialGoodsDesc[$key],
                    'goods_price' => $specialGoodsPrice[$key],
                    'status' => mShopSpecialGoods::STATUS_PASSED
                ];
            } else {
                throw new Exception('添加专题商品失败');
            }
        }
        if ($specialTemplGoods) {
            $goodsIds = mShopSpecialGoods::getList(['special_id' => $specialId,], 'goods_id');
            $changeGoodsIds = array_intersect($goodsIds, $specialGoods);
            foreach ($changeGoodsIds as $goodsId) {
                $result = mShopSpecialGoods::updateSpecialGoods(['special_id' => $specialId, 'goods_id' => $goodsId], $specialTemplGoods[$goodsId]);
                if (!$result) {
                    throw new Exception('添加专题商品失败');
                }
            }
            $addGoodsIds = array_diff($specialGoods, $goodsIds);
            foreach ($addGoodsIds as $goodsId) {
                $result = mShopSpecialGoods::addSpecialGoods($specialTemplGoods[$goodsId]);
                if (!$result) {
                    throw new Exception('添加专题商品失败');
                }
            }
        } else {
            throw new Exception('添加专题商品失败');
        }
        return true;
    }

    public static function admDeleSpecialById($specialId)
    {
        return mShopSpecial::deleSpecialById($specialId);
    }


    public static function admGetSpecialPage($specialId)
    {
        $result = mShopSpecial::getSpecialPage();
        $specialKey = array_search($specialId, $result);
        $specialKey++;
        return $specialKey;
    }

    /*
     * 查询单条
     * **/
    public static function admGetSpecialInfoById($specialId, $field = '*')
    {

        $specialInfo = mShopSpecial::getSpecialInfoById($specialId, mShopSpecial::TYPE_SPECIAL_GOODS, $field);
        $specialInfo['shop_img_hash'] = $specialInfo['shop_img'];
        $specialInfo['special_info_img_hash'] = $specialInfo['special_info_img'];
        $specialInfo['share_img_hash'] = $specialInfo['share_img'];
        self::formatInfo($specialInfo);

        $field = ['id', 'special_id', 'sort'];
        $specialTempls = mShopSpecialTempl::getSpecialTemplBySpecialId($field, $specialId);
        $templIds = array_column($specialTempls, 'id');
        $goodsList = mShopSpecialGoods::getList(['templ_id' => $templIds, 'status' => mShopSpecialGoods::STATUS_PASSED], '*');
        $specialGoods = [];
        foreach ($goodsList as $row) {
            $specialGoods[$row['templ_id']] = $row;
        }

        foreach ($specialTempls as $key => $value) {
            if (isset($specialGoods[$value['id']])) {
                $specialTempls[$key]['goods_id'] = $specialGoods[$value['id']]['goods_id'];
                $specialTempls[$key]['goods_desc'] = $specialGoods[$value['id']]['goods_desc'];
                $specialTempls[$key]['goods_price'] = $specialGoods[$value['id']]['goods_price'];
            } else {
                unset($specialTempls[$key]);
            }
        }
        $specialInfo['son'] = $specialTempls;

        return $specialInfo;
    }

    public static function getSpecialList($limit, $where)
    {
        $time = date('Y-m-d H:i:s');
        $where['start_time'] = $where['status'] ? $time : '';
        $where['end_time'] = $where['status'] ? $time : '';

        $where = [
            'special_type' => mShopSpecial::TYPE_SPECIAL_GOODS,
            'id' => $where['special_id'],
            'special_title[~]' => $where['special_title'],
            'start_time[<]' => $where['start_time'] ?: '',
            'end_time[>=]' => $where['end_time'] ?: '',
            'status' => mShopSpecial::STATUS_NORMAL
        ];

        $where = array_filter($where);
        $specialList = mShopSpecial::getSpecialList($where, ['sort' => 'DESC'], $limit);
        $specialList = sCarouselBanner::getCalculationDiff($specialList);
        $specialList = array_map(function ($v) {
            $v['preview'] = toolsBizUrl::h5SpecialInfo($v['id']);
            return $v;
        }, $specialList);

        $sensorsdataConf = tSensorsApi::getCourierBirdConfig('api');
        $product = (isset($_SERVER['APP_ENV']) && $_SERVER['APP_ENV'] == "production") ? 0 : 0;

        if ($product) {
            $specialList = array_map(function ($v) use ($sensorsdataConf, $product) {
                $clicks = 0;
                if ($v['is_large_special']) {
                    $type = 'mall_guide_large';
                } else {
                    $type = 'mall_guide_small';
                }
                $clicks = tSensorsApi::clicks('correlation', $type, 'obj_id', $v['id'], $sensorsdataConf);
                $v['clicks'] = $clicks ?: 0;
                return $v;
            }, $specialList);
        }

        $result = [
            'specialList' => $specialList,
            'specialCount' => mShopSpecial::getSpecialCount($where)
        ];

        return $result;
    }

    public static function getSpecialInfo($specialId, $areaCode)
    {

        $data = self::formatSpecialInfo($specialId, $areaCode);
        if ($data['is_end'] == 0) {
            $data['relation_id'] = array_filter(explode(',', $data['relation_id']));
            $data['relation_id'] = $data['relation_id'] ? $data['relation_id'] : [];
            if (!$data['relation_id']) {
                $specialIds = cShopRecommendSpecial::getSpecial(self::SMALL_PROGRAM_SPECIAL);
                if (is_null($specialIds)) {
                    $time = date("Y-m-d H:i:s");
                    $specialIds = mShopSpecial::specialList($time, mShopSpecial::TYPE_SPECIAL_GOODS, 'id');
                    cShopRecommendSpecial::setSpecial(self::SMALL_PROGRAM_SPECIAL, $specialIds);
                }
                $specialIds = array_diff($specialIds, [$specialId]);
                if (count($specialIds) > 5) {
                    $data['relation_id'] = array_rand(array_flip($specialIds), 5);
                } else {
                    $data['relation_id'] = $specialIds;
                }
            }

            $list = [];
            foreach ($data['relation_id'] as $value) {
                $specialInfo = self::formatSpecialInfo($value, $areaCode, true);
                $link = tBizUrl::h5SpecialInfo($value);
                $specialInfo['inner_link'] = $link . self::INNER_LINK . 'inthematic=2&';
                $specialInfo['outer_link'] = $link . self::OUTER_LINK . 'inthematic=2&';
                if ($specialInfo['is_end'] == 0) {
                    $list[] = $specialInfo;
                }
            }


            $data['recommend'] = $list;
        }

        $array = [
            'rows' => $data ?: []
        ];

        return $array;
    }

    public static function getInfoBySpecialId($specialId)
    {
        self::_getSpecialData($specialId);
        if (is_null(self::$cacheSpecialData[$specialId])) {

            $list['info'] = self::getSpecial($specialId);
            if (!$list['info']) {

                throw new \Exception($specialId . '专题不存在');
            }

            $templList = mShopSpecialTempl::getTemplListBySpecialId($specialId);
            $goodsList = mShopSpecialGoods::getSpecialGoodsInfoBySpecialIds($specialId);
            $templGoods = [];
            foreach ($goodsList as $goodsInfo) {
                $templGoods[$goodsInfo['templ_id']][$goodsInfo['goods_id']] = $goodsInfo;
            }
            foreach ($templList as &$row) {
                $templId = $row['id'];
                $goodsIds = isset($templGoods[$templId]) ? array_keys($templGoods[$templId]) : [];
                $row['goods_ids'] = $goodsIds;
                $row['goods_id'] = $goodsIds ? implode(',', $goodsIds) : '';
                $row['goods'] = isset($templGoods[$templId]) ? $templGoods[$templId] : [];
            }
            $list['templ_list'] = $templList;
            cShopSpecial::setSpecial($specialId, $list);
            self::$cacheSpecialData[$specialId] = $list;
        }
    }

    /*
     * 只是起到处理数据的作用
     * 注意只能用于获取专题商品信息，活动不能使用该方法
     * **/
    public static function formatSpecialInfo($specialId, $areaCode = 0, $limitCount = false)
    {
        self::getInfoBySpecialId($specialId);
        $specialInfo = self::$cacheSpecialData[$specialId]['info'];
        $specialTempList = self::$cacheSpecialData[$specialId]['templ_list'];
        $specialInfo['is_end'] = time() > strtotime($specialInfo['end_time']) ? 1 : 0;
        if ($specialInfo['is_end'] == 0) {
            $goodsIds = array_column($specialTempList, 'goods_id');
            if ($limitCount) {
                $goodsIds = array_slice($goodsIds, 0, 3);
                $specialTempList = array_slice($specialTempList, 0, 3);
            }
            $goodsInfo = sGoods::goods($goodsIds, sGoods::FIELDS_GROUP_LIST, ['area_code' => $areaCode, 'activity_type' => ActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE]);
            $goods = self::addgoodsDescToSpecialInfo($goodsInfo, $specialTempList); // 专题商品简介添加至商品详情
            $specialInfo['goods'] = $goods ?: [];
            $specialInfo['share_info'] = sShare::getSpecialShare($specialInfo); // 获取分享信息
        }

        return $specialInfo;
    }

    public static function formatGoodsIds($goodsInfo)
    {
        foreach ($goodsInfo['goods'] as $val) {

            $data = sGoodsDetail::formatBasicInfos($val['goods_id']);
            $data = array_shift($data);

            if ($data['status'] == 2 && $data['stock'] > 0) {

                $goods[] = $val;
            }
        }

        $goodsInfo['goods'] = $goods ?: [];

        return $goodsInfo;
    }

    public static function updateClicks($specialId)
    {

        self::_async($specialId);
    }

    public static function _async_updateClicks($specialId)
    {

        try {

            $result = mShopSpecial::update(['clicks[+]' => 1], [
                'id' => $specialId
            ]);
            $result->rowCount();

        } catch (\Exception $e) {

            tLog::warning('增加专题点击量异常', [
                'specialId' => $specialId,
                'edittime' => date('Y-m-d H:i:s', time()),
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine()
            ]);
            throw $e;
        }
    }

    /*
     * 获取专题详细信息
     * **/
    public static function getSpecial($specialId, $specialInfoField = "*")
    {
        $specialInfo = mShopSpecial::getSpecialInfo($specialId, $specialInfoField);
        self::formatInfo($specialInfo);
        return $specialInfo;
    }

    /*
     * 将专题商品简介添加至对应的商品详情
     * **/
    public static function addgoodsDescToSpecialInfo($goodsInfo, $specialTemplInfo)
    {
        $goodsInfo = array_column($goodsInfo, null, 'id');
        $goodsInfos = array_map(function ($v) use ($goodsInfo) {
            $goodsId = $v['goods_id'] ? $v['goods_id'] : '';//因为专题都是一行一个商品，所以取第一个
            if ($goodsId) {
                if (isset($goodsInfo[$goodsId]) && $goodsInfo[$goodsId]) {
                    $goodsInfos = $goodsInfo[$goodsId];
                    if ($goodsInfo[$goodsId]['actual_stock'] <= 0) {
                        $goodsInfos['status'] = mGoodsBasicInfo::STATUS_APP_OFFLINE;
                    }
                    $goodsInfos['goods_id'] = $goodsId;
                    $goodsInfos['spec_img'] = $goodsInfo[$goodsId]['cover_img'] ?: '';
                    $goodsInfos['goods_desc'] = $v['goods'][$goodsId]['goods_desc'] ?: '';
                    $goodsInfos['goods_price'] = $v['goods'][$goodsId]['goods_price'] ?: '';

                    if (!empty($goodsInfo[$goodsId]['active_list'])) {
                        $icon = array_shift($goodsInfo[$goodsId]['active_list']);
                        $goodsInfos['icon'] = $icon['icon'];
                    } else if ($goodsInfo[$goodsId]['active_icon_list']) {
                        $goodsInfos['icon'] = $goodsInfo[$goodsId]['active_icon_list'][0];
                    }
                    return $goodsInfos;
                }
            }
        }, $specialTemplInfo);

        return $goodsInfos ? array_values(array_filter($goodsInfos)) : [];
    }

    public static function admGetSpecialList($specialType, $time = '', $id = 0, $limit, $order)
    {
        $where = [
            'special_type' => $specialType,
        ];
        if ($time) {
            $where['start_time[<]'] = $time;
            $where['end_time[>=]'] = $time;
        }

        if ($id) {
            $where['id'] = $id;
        }
        $list = mShopSpecial::getSpecialList($where, $order, $limit);
        return $list;
    }

    public
    static function admGetSpecialListCount($specialType, $time = '', $id = 0)
    {
        $where = [
            'special_type' => $specialType,
        ];
        if ($time) {
            $where['start_time[<]'] = $time;
            $where['end_time[>=]'] = $time;
        }
        if ($id) {
            $where['id'] = $id;
        }
        $count = mShopSpecial::getSpecialListCount($where);
        return $count;
    }

    public static function getactivityInfo($specialId, $areaCode)
    {
        $specialAllInfo = self::getSpecialAllInfo($specialId, $areaCode);
        if (!$specialAllInfo) {
            throw new \Exception('活动不存在');
        }
        $activityTempList = $specialAllInfo['templ_list'];
        $goodsInfos = $specialAllInfo['goods_list'];

        $list = [];
        foreach ($activityTempList as $activityTempl) {
            $tempInfo = [
                'id' => $activityTempl['id'],
                'type' => $activityTempl['type'],
                'special_id' => $activityTempl['special_id'],
                'goods_id' => $activityTempl['goods_id'],
                'goods_desc' => $activityTempl['goods_desc'],
                'sort' => $activityTempl['sort'],
                'status' => $activityTempl['status'],
                'coupon_id' => $activityTempl['coupon_id'],
                'coupon_ids' => $activityTempl['coupon_ids'],
                'banner_img_url' => $activityTempl['banner_img_url'],
                'link_param' => $activityTempl['link_url'],
                'link_url' => tLink::format($activityTempl['link_id'], $activityTempl['link_url']),
                'link_target' => $activityTempl['link_id']
            ];
            $i = 0;
            if (!empty($activityTempl['goods'])) {
                foreach ($activityTempl['goods'] as $k => $v) {
                    if (isset($goodsInfos[$v['goods_id']]) && $goodsInfos[$v['goods_id']]) {
                        $tempInfo['goods'][$i] = $goodsInfos[$v['goods_id']];
                        $tempInfo['goods'][$i]['spec_img'] = $goodsInfos[$v['goods_id']]['cover_img'] ?: '';
                        $tempInfo['goods'][$i]['goods_id'] = $k;
                        $tempInfo['goods'][$i]['goods_desc'] = $v['goods_desc'] ?: '';
                        $tempInfo['goods'][$i]['goods_price'] = $v['goods_price'] ?: '';
                        if ($goodsInfos[$v['goods_id']]['actual_stock'] <= 0) {
                            $tempInfo['goods'][$i]['status'] = mGoodsBasicInfo::STATUS_APP_OFFLINE;
                        }
                        if (!empty($goodsInfos[$v['goods_id']]['active_list'])) {
                            $icon = array_shift($goodsInfos[$v['goods_id']]['active_list']);
                            $tempInfo['goods'][$i]['icon'] = $icon['icon'];
                        } else if ($goodsInfos[$v['goods_id']]['active_icon_list']) {
                            $tempInfo['goods'][$i]['icon'] = $goodsInfos[$v['goods_id']]['active_icon_list'][0];
                        }
                        $i++;
                    }
                }
            }
            $list[] = $tempInfo;
        }
        $activityInfo = [
            'id' => $specialAllInfo['id'],
            'special_title' => $specialAllInfo['special_title'],
            'special_type' => $specialAllInfo['special_type'],
            'special_bgcolor' => $specialAllInfo['special_bgcolor'],
            'shop_img' => $specialAllInfo['shop_img'],
            'special_info_img' => $specialAllInfo['special_info_img'],
            'special_desc' => $specialAllInfo['special_desc'],
            'share_title' => $specialAllInfo['share_title'],
            'share_desc' => $specialAllInfo['share_desc'],
            'share_img' => $specialAllInfo['share_img'],
            'relation_id' => array_filter(explode(',', $specialAllInfo['relation_id'])),
            'is_end' => $specialAllInfo['is_end'],
        ];
        $activityInfo['list'] = $list;
        $activityInfo['share_info'] = sShare::getActivityShare($activityInfo); // 获取分享信息

        //推荐活动
        $recommend = [];
        //随机推荐活动5个（暂时不用随机推活动）
//        if (!$activityInfo['relation_id']) {
//            $time = date("Y-m-d H:i:s");
//            $specialIds = mShopSpecial::specialList($time, null, 'id', ['sort' => 'DESC'], [0, 50]);
//            $specialIds = array_diff($specialIds, [$specialId]);
//            if (count($specialIds) > 5) {
//                $activityInfo['relation_id'] = array_rand(array_flip($specialIds), 5);
//            } else {
//                $activityInfo['relation_id'] = $specialIds;
//            }
//        }

        foreach ($activityInfo['relation_id'] as $relationId) {
            $specialInfo = self::getActivityRecommend($relationId, $areaCode);
            if ($specialInfo) {
                if ($specialInfo['special_type'] == mShopSpecial::TYPE_SPECIAL_GOODS) {
                    $link = tBizUrl::h5SpecialInfo($relationId);
                    $specialInfo['inner_link'] = $link . self::INNER_LINK . 'inthematic=2&';
                    $specialInfo['outer_link'] = $link . self::OUTER_LINK . 'inthematic=2&';
                } else {
                    $link = tBizUrl::h5ShopActivity($relationId);
                    $specialInfo['inner_link'] = $link . self::INNER_LINK;
                    $specialInfo['outer_link'] = $link . self::OUTER_LINK;
                }

                $recommend[] = $specialInfo;
            }

        }
        $activityInfo['recommend'] = $recommend;

        $data = ['rows' => $activityInfo ?: []];

        return $data;

    }

    private static function getActivityRecommend($specialId, $provinceId, $recommendGoodsCount = 4)
    {
        $recommendSpecialInfo = [];
        $specialAllInfo = self::getSpecialAllInfo($specialId, $provinceId, $recommendGoodsCount);
        if ($specialAllInfo) {
            $activityTempList = $specialAllInfo['templ_list'];
            $goodsInfos = $specialAllInfo['goods_list'];
            $recommendSpecialInfo = [
                'id' => $specialAllInfo['id'],
                'special_title' => $specialAllInfo['special_title'],
                'special_bgcolor' => $specialAllInfo['special_bgcolor'],
                'special_type' => $specialAllInfo['special_type'],
                'shop_img' => $specialAllInfo['shop_img'],
                'special_info_img' => $specialAllInfo['special_info_img'],
                'special_desc' => $specialAllInfo['special_desc'],
                'share_title' => $specialAllInfo['share_title'],
                'share_desc' => $specialAllInfo['share_desc'],
                'share_img' => $specialAllInfo['share_img'],
                'relation_id' => array_filter(explode(',', $specialAllInfo['relation_id'])),
                'is_end' => $specialAllInfo['is_end'],
            ];
            $recommendSpecialInfo['goods'] = [];
            foreach ($activityTempList as $activityTempl) {
                $i = 0;
                foreach ($activityTempl['goods'] as $k => $v) {
                    if (isset($goodsInfos[$v['goods_id']]) && $goodsInfos[$v['goods_id']]) {
                        $goods = $goodsInfos[$v['goods_id']];
                        $goods['spec_img'] = $goodsInfos[$v['goods_id']]['cover_img'] ?: '';
                        $goods['goods_id'] = $k;
                        $goods['goods_desc'] = $v['goods_desc'] ?: '';
                        $goods['goods_price'] = $v['goods_price'] ?: '';
                        if ($goodsInfos[$v['goods_id']]['actual_stock'] <= 0) {
                            $goods['status'] = mGoodsBasicInfo::STATUS_APP_OFFLINE;
                        }
                        if (!empty($goodsInfos[$v['goods_id']]['active_list'])) {
                            $icon = array_shift($goodsInfos[$v['goods_id']]['active_list']);
                            $goods['icon'] = $icon['icon'];
                        } else if ($goodsInfos[$v['goods_id']]['active_icon_list']) {
                            $goods['icon'] = $goodsInfos[$v['goods_id']]['active_icon_list'][0];
                        }
                        $i++;
                        $recommendSpecialInfo['goods'][] = $goods;
                    }
                }

            }
        }
        return ($recommendSpecialInfo && isset($recommendSpecialInfo['goods']) && $recommendSpecialInfo['goods']) ? $recommendSpecialInfo : [];
    }

    private static function getSpecialAllInfo($specialId, $provinceId, $recommendGoodsCount = 0)
    {
        self::getInfoBySpecialId($specialId);
        $specialInfo = self::$cacheSpecialData[$specialId]['info'];
        $templList = self::$cacheSpecialData[$specialId]['templ_list'];
        $specialAllInfo = [];
        if ($specialInfo) {
            $specialInfo['is_end'] = time() > strtotime($specialInfo['end_time']) ? 1 : 0;
            if ($specialInfo['is_end'] == 0) {
                $goodsList = [];
                $goodsIds = [];
                if ($recommendGoodsCount) {
                    $activityTempList = [];
                } else {
                    $activityTempList = $templList;
                }
                foreach ($templList as $templInfo) {
                    if (isset($templInfo['goods_ids']) && $templInfo['goods_ids']) {
                        if ($recommendGoodsCount) {
                            if (count($goodsIds) >= $recommendGoodsCount) {
                                break;
                            }
                            $activityTempList[] = $templInfo;
                        }
                        $goodsIds = $templInfo['goods_ids'] ? array_merge($goodsIds, $templInfo['goods_ids']) : $goodsIds;
                        $goodsIds = array_unique($goodsIds);
                    }
                }
                //活动里商品个数小于需要推荐商品数量3,则不推荐该活动
                if (count($goodsIds) < $recommendGoodsCount) {
                    return [];
                }
                $goodsInfos = array_map(function ($goodsId) use ($provinceId) {
                    $goodsInfo = sGoods::goods($goodsId, sGoods::FIELDS_GROUP_LIST, ['area_code' => $provinceId, 'activity_type' => ActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE]); // 获取商品详细信息
                    return $goodsInfo;

                }, $goodsIds);

                foreach ($goodsInfos as $val) {
                    $goodsList[$val['id']] = $val;
                }
                $specialAllInfo = $specialInfo;
                $specialAllInfo['templ_list'] = $activityTempList;
                $specialAllInfo['goods_list'] = $goodsList;
            }
        }
        return $specialAllInfo;
    }

    /*
     * 小程序专题列表
     * **/
    public static function specialList($page, $pageSize)
    {
        $specialIdList = cShopRecommendSpecial::getSpecial(self::SMALL_PROGRAM_SPECIAL);
        if (is_null($specialIdList)) {
            $time = date("Y-m-d H:i:s");
            $specialIdList = mShopSpecial::specialList($time, mShopSpecial::TYPE_SPECIAL_GOODS, 'id');
            cShopRecommendSpecial::setSpecial(self::SMALL_PROGRAM_SPECIAL, $specialIdList);
        }

        $start = ($page - 1) * $pageSize;
        $specialIdList = array_slice($specialIdList, $start, $pageSize);
        $list = array_map(function ($v) {
            $goodsData = self::formatSpecialInfo($v, 0, true);
            $list['id'] = $v;
            $list['special_info_img'] = self::$cacheSpecialData[$v]['info']['special_info_img'];
            $list['goods'] = $goodsData['goods'];
            return $list;
        }, $specialIdList);

        $is_over = 0;
        if (count($specialIdList) != 10) {
            $is_over = 1;
        }

        $array = [
            'rows' => $list,
            'is_over' => $is_over
        ];

        return $array ?: [];
    }

    public static function formatInfo(&$info)
    {
        if ($info) {
            foreach ($info as $key => $value) {
                switch ($key) {
                    case 'special_info_img' :
                        $info['special_info_img'] = $info['special_info_img'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $info['special_info_img'], ImgUrl::IMAGE_SIZE_OP_ORI) : '';
                        break;
                    case 'share_img' :
                        $info['share_img'] = $info['share_img'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $info['share_img'], ImgUrl::IMAGE_SIZE_SQ_PHONE) : '';
                        break;
                    case 'shop_img' :
                        $info['shop_img'] = $info['shop_img'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $info['shop_img'], ImgUrl::IMAGE_SIZE_OP_ORI) : '';
                        break;
                    case 'special_icon' :
                        $info['special_icon'] = $info['special_icon'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $info['special_icon'], ImgUrl::IMAGE_SIZE_OP_ORI) : '';
                        break;
                    case 'special_banner' :
                        $info['special_banner'] = $info['special_banner'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $info['special_banner'], ImgUrl::IMAGE_SIZE_OP_ORI) : '';
                        break;
                }
            }
        }
    }

    public static function formatGoodsInfo($goodsInfo)
    {

        foreach ($goodsInfo as $key => $value) {

            $goodsInfo[$key]['spec_img'] = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $value['spec_img'], ImgUrl::IMAGE_SIZE_O_500);
        }

        return $goodsInfo;
    }


    /**
     * 添加活动模板商品(调用级需要加事物,仅编辑活动商品时使用)
     * @param $data 模板商品数组集合
     * @return mixed
     */
    public static function admAddTemplGoods($data)
    {
        $templIds = array_column($data, 'templ_id');
        $list = mShopSpecialGoods::getList(['templ_id' => $templIds]);
        $hasTemplGoods = [];
        foreach ($list as $row) {
            $hasTemplGoods[$row['templ_id']][] = $row['goods_id'];
        }
        $goodsData = [];
        foreach ($data as $row) {
            $specialId = $row['special_id'];
            $specialType = $row['special_type'];
            $templId = $row['templ_id'];
            $goodsId = $row['goods_id'];
            $goodsData[$templId][$goodsId] = [
                'special_id' => $specialId,
                'special_type' => $specialType,
                'templ_id' => $templId,
                'goods_id' => $goodsId,
                'goods_desc' => isset($row['goods_desc']) ? $row['goods_desc'] : '',
                'goods_price' => isset($row['goods_price']) ? $row['goods_price'] : 0,
                'status' => mShopSpecialGoods::STATUS_PASSED,
            ];
        }
        $insertGoodsData = [];
        $changeGoodsData = [];
        $delGoodsData = [];
        foreach ($goodsData as $templId => $row) {
            $goodsIds = array_keys($row);//1,2
            if (isset($hasTemplGoods[$templId])) {
                $hasGoodsIds = $hasTemplGoods[$templId];//1,3,4
                $changeGoodsIds = array_intersect($goodsIds, $hasGoodsIds);
                if ($changeGoodsIds) {
                    $changeGoodsData[$templId] = $changeGoodsIds;
                }
                $delGoodsIds = array_diff($hasGoodsIds, $goodsIds);
                if ($delGoodsIds) {
                    $delGoodsData[$templId] = $delGoodsIds;
                }
                $insertGoodsIds = array_diff($goodsIds, $hasGoodsIds);
                if ($insertGoodsIds) {
                    $insertGoodsData[$templId] = $insertGoodsIds;
                }
            } else {
                $insertGoodsData[$templId] = $goodsIds;
            }
        }
        if ($insertGoodsData) {
            $insertData = [];
            foreach ($insertGoodsData as $templId => $goodsIds) {
                foreach ($goodsIds as $goodsId) {
                    $insertData[] = $goodsData[$templId][$goodsId];
                }
            }
            $result = mShopSpecialGoods::addSpecialGoods($insertData);
            if (!$result) {
                return false;
            }
        }
        if ($changeGoodsData) {
            foreach ($changeGoodsData as $templId => $goodsIds) {
                foreach ($goodsIds as $goodsId) {
                    $changeData = $goodsData[$templId][$goodsId];
                    $result = mShopSpecialGoods::updateSpecialGoods(['templ_id' => $templId, 'goods_id' => $goodsId], $changeData);
                    if (!$result) {
                        return false;
                    }
                }
            }
        }
        if ($delGoodsData) {
            foreach ($delGoodsData as $templId => $goodsIds) {
                foreach ($goodsIds as $goodsId) {
                    $delData['status'] = mShopSpecialGoods::STATUS_DELECT;
                    $result = mShopSpecialGoods::updateSpecialGoods(['templ_id' => $templId, 'goods_id' => $goodsId], $delData);
                    if (!$result) {
                        return false;
                    }
                }
            }
        }
        return true;
    }


    /**
     * 获取可以报名的活动列表
     **/
    public static function getActivityList()
    {
        return mShopSpecial::getActivityList(['id', 'special_title']);
    }

    public static function getRegisterSpecialInfos($goodsIds, $onlyValid = true, $specialType = mShopSpecial::TYPE_SPECIAL_REGISTER, $registerId = 0)
    {
        $where = [
            'goods_id' => $goodsIds,
            'status' => mSelectGoodsLog::STATUS_NORMAL,
            'type' => AllActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE
        ];
        if ($registerId) $where['register_id'] = $registerId;

//    	$registerGoodsInfos = ActivityRegisterGoods::getRegisterGoods($where);
        $registerGoodsInfos = mSelectGoodsLog::select('*', $where);
        $specialIdsGrpByGoodsIds = [];
        //  将 活动ID 以 商品ID 聚合
        foreach ($registerGoodsInfos as $registerGoodsInfo) {
            if (!isset($specialIdsGrpByGoodsIds[$registerGoodsInfo['goods_id']]) || !in_array($registerGoodsInfo['activity_id'], $specialIdsGrpByGoodsIds[$registerGoodsInfo['goods_id']])) {
                $specialIdsGrpByGoodsIds[$registerGoodsInfo['goods_id']][] = $registerGoodsInfo['activity_id'];
            }
        }

        $specialIds = array_column($registerGoodsInfos, 'activity_id');
        if($specialIds) {
            $shopSpecials = mShopSpecial::getInfosBySpcialIdsAndType($specialIds, $specialType, $onlyValid ? date("Y-m-d H:i:s") : null);
            $shopSpecials = array_column($shopSpecials, null, 'id');
            $results = [];
            foreach ($specialIdsGrpByGoodsIds as $goodsId => $specialIds) {
                foreach ($specialIds as $specialId) {
                    if ($specialId) {
                        $results[$goodsId][$specialId] = $shopSpecials[$specialId];
                    }
                }
            }
        }
        return $results;


//    	$where = [
//			'goods_id' => $goodsIds,
//			'status' => mShopSpecialGoods::STATUS_PASSED,
//			'special_type' => $specialType,
//		];
//    	if ($registerId) { // 存在报名活动ID  取 从此报名活动中被选中的活动
//    		$registerGoodsInfos = ActivityRegisterGoods::getRegisterGoods([
//				'goods_id' => $goodsIds,
//				'register_id' => $registerId,
//			]);
//    		$specialIds = array_column($registerGoodsInfos, 'special_id');
//    		$where['special_id'] = $specialIds;
//		}
//        $specialGoods = mShopSpecialGoods::getList($where);
//
//        $specialGoodsBySpecialId = [];
//        foreach ($specialGoods as $row) {
//            $specialGoodsBySpecialId[$row['special_id']][] = $row['goods_id'];
//        }
//
//        $results = [];
//        if ($specialGoodsBySpecialId) {
//            $shopSpecials = mShopSpecial::getInfosBySpcialIdsAndType(array_keys($specialGoodsBySpecialId), $specialType, $onlyValid ? date('Y-m-d H:i:s') : null);
//            $shopSpecials = array_column($shopSpecials, null, 'id');
//            foreach ($specialGoodsBySpecialId as $specialId => $tmpgoodsIds) {
//                foreach ($tmpgoodsIds as $goodsId) {
//                    if (isset($shopSpecials[$specialId]) && !isset($results[$goodsId][$specialId]))
//                        $results[$goodsId][$specialId] = $shopSpecials[$specialId];
//                }
//            }
//        }
//        return $results;

    }

}